//
//  ViewController.m
//  27-WeekendHomework
//
//  Created by dllo on 16/8/19.
//  Copyright © 2016年 ZHW. All rights reserved.
//

#import "ViewController.h"
#import "MusciPlayView.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) MusciPlayView *musicPlayView;
@property (nonatomic, strong) NSTimer *myTimer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"vc_bg"]];
    [self setUpAVPlayer];
    
    self.musicPlayView = [[MusciPlayView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_musicPlayView];
    _musicPlayView.endTime.text = [NSString stringWithFormat:@"%d:%02d", (int)_audioPlayer.duration/ 60 , (int)_audioPlayer.duration % 60];

    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateSliderProgress:) userInfo:nil repeats:YES];
 
    [_musicPlayView play:^(UIButton *play) {
        [_audioPlayer play];
    } pause:^(UIButton *pause) {
        [_audioPlayer pause];
    }];
    
    [_musicPlayView slider:^(UISlider *slider) {
        _audioPlayer.currentTime = slider.value;
    }];
   
}

- (void)setUpAVPlayer {
    NSString *musicStr = [[NSBundle mainBundle] pathForResource:@"陈奕迅 - 倾城" ofType:@"mp3"];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicStr] error:nil];
    [_audioPlayer prepareToPlay];
    _audioPlayer.volume = 1.0;

}

- (void)updateSliderProgress:(NSTimer *)timer {
    [_musicPlayView.slider setValue:_audioPlayer.currentTime];
    _musicPlayView.changedTime.text = [NSString stringWithFormat:@"%d:%02d", (int)_musicPlayView.slider.value/ 60 , (int)_musicPlayView.slider.value % 60];
    [_musicPlayView.slider setMinimumValue:0.0];
    [_musicPlayView.slider setMaximumValue:[_audioPlayer duration]];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
